﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace DO.Common
{
	public static class WebBrowser 
	{
		/// <summary>
		/// 取得cookie及回傳html
		/// </summary>
		/// <param name="url"></param>
		/// <param name="param"></param>
		/// <param name="method"></param>
		/// <param name="cookie"></param>
		/// <param name="referer"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static string getHTML(string url, string param, string method, CookieContainer cookie, string encoding)
		{
			HttpWebRequest request;
			HttpWebResponse response;
			string result;

			try
			{
				if (method.Equals("GET") && param != null)
				{
					request = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param);
				}
				else
				{
					request = (HttpWebRequest)HttpWebRequest.Create(url);
				}
				//設定Header模擬瀏覽器
				request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)";
				request.Method = method;
				request.ContentType = "application/x-www-form-urlencoded";
				request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

				if (cookie != null)
				{
					request.CookieContainer = cookie;
				}

				if (param != null && method.Equals("POST"))
				{
					byte[] bs = Encoding.ASCII.GetBytes(param);
					request.ContentLength = bs.Length;
					using (Stream reqStream = request.GetRequestStream())
					{
						reqStream.Write(bs, 0, bs.Length);
					}
				}

				using (response = (HttpWebResponse)request.GetResponse())
				{
					
					StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
					result = reader.ReadToEnd();

					if (cookie != null)
					{
						cookie = request.CookieContainer;
						cookie.Add(response.Cookies);
					}
				}
				return result;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

	}
}
